﻿#include "TxWorkerWidget.h"
#include "ui_TxWorkerWidget.h"

#include <QTabBar>
#include <QLineEdit>
#include <QPushButton>

#include "GlobalDefine.h"
#include "GlobalData.h"

class TxWorkerWidget::TxWorkerWidgetPrivate :public QObject
{
public:
	QLineEdit	* edt_label;
	QPushButton	* corner_widget;
	AstWorker* ast_worker;

	int scene_count;		// 计数
public:
	TxWorkerWidgetPrivate(QObject*parent):QObject(parent)
	{
		edt_label = nullptr;
		corner_widget = nullptr;

		scene_count = 0;
		ast_worker = nullptr;
	}

	int newSceneID()
	{
		return ++scene_count;
	}

};

TxWorkerWidget::TxWorkerWidget(QWidget *parent)
	: QWidget(parent),private_ptr(new TxWorkerWidgetPrivate(this))
{
	ui = new Ui::TxWorkerWidget();
	ui->setupUi(this);

	QStringList lst = GlobalData::instance()->ast()->sceneNames(AstScene::SCENE_WORKER).split(",");

	ui->cbx_scene->addItems(lst);

	ui->tabWidget->tabBar()->setTabButton(0, QTabBar::RightSide, nullptr);

	private_ptr->corner_widget = new QPushButton(ui->tabWidget);
	ui->tabWidget->setCornerWidget(private_ptr->corner_widget, Qt::Corner::TopLeftCorner);

	private_ptr->edt_label = new QLineEdit(ui->tabWidget->tabBar());
	private_ptr->edt_label->hide();
}

TxWorkerWidget::~TxWorkerWidget()
{
	delete ui;
}

//void TxWorkerWidget::setAstWorker(AstWorker*_)
//{
//	private_ptr->ast_worker = _;
//}
static int tabIndexOf(QTabWidget*p, const QString&s)
{
	int count = p->count();
	for (int i = 0; i < count; i++) {
		if (s == p->tabText(i)) {
			return i;
		}
	}
	return -1;
}

void TxWorkerWidget::on_btn_create_clicked()
{
	QString name = ui->cbx_scene->currentText();
	QString label = ui->edt_scenename->text();
	if (label.isEmpty())
		label = QString("w-%1").arg(private_ptr->newSceneID());

	int idx = tabIndexOf(ui->tabWidget, label);
	if (idx >= 0) {
		ui->tabWidget->setCurrentIndex(idx);
		return;
	}

	AstScene* as = GlobalData::instance()->ast()->createScene(name, AstScene::SCENE_WORKER, label);
	//as->widget()->setUserData(0, (QObjectUserData*)as);
	idx = ui->tabWidget->addTab(as->widget(), label);
	ui->tabWidget->setCurrentIndex(idx);
}


void TxWorkerWidget::on_tabWidget_tabCloseRequested(int idx)
{
	QString s = ui->tabWidget->tabText(idx);
	GlobalData::instance()->ast()->closeScene(AstScene::SCENE_WORKER, s);
	ui->tabWidget->removeTab(idx);
}

void TxWorkerWidget::on_tabWidget_tabBarDoubleClicked(int idx)
{
	if (idx < 0)
		return;

	QTabBar*tb = ui->tabWidget->tabBar();
	QRect rc = tb->tabRect(idx);

	QWidget*w = tb->tabButton(idx, QTabBar::ButtonPosition::RightSide);
	if (w) {
		QRect r = w->rect();
		r = w->geometry();
		rc.setRight(r.left());
	}
	//rc.setWidth(rc.width() / 2);
	rc.adjust(1, 1, -1, -1);
	private_ptr->edt_label->setText(tb->tabText(idx));
	private_ptr->edt_label->setGeometry(rc);
	private_ptr->edt_label->show();
	//ui->tabWidget->setCornerWidget();

	
}
